require 'rubygems'
require 'jmx4r'
require "#{ENV['HOME']}/Oracle_111160/Middleware/wlserver_10.3/server/lib/wljmxclient.jar"

java_import 'javax.management.ObjectName'
java_import java.lang.System
System.setProperty("jmx.remote.protocol.provider.pkgs", "weblogic.management.remote")

class JMXConnection
  
  attr_reader :conn
  attr_accessor :user, :passwd, :url, :mbean_name
  
  def initialize
    @user = "weblogic"
    @passwd = "qwer1234"
    @url = "service:jmx:iiop://ampadmdv-ua01.intropro.com.ua:7001/jndi/weblogic.management.mbeanservers.domainruntime"
#     @url = "service:jmx:iiop://ampsoadv-ua01.intropro.com.ua:8001/jndi/weblogic.management.mbeanservers.runtime"
#     @mbean_name = "com.bea:Name=ua_dv_soa_server1,Location=ua_dv_soa_server1,Type=ServerRuntime"
    @mbean_name = "com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean"
    connect
  end
  
  def close
    @conn.close unless !@conn
  end
  
  def connect
    @conn = JMX::MBean.establish_connection :url => @url, :username => @user, :password => @passwd
  end
  
  def display_soainfra_attrs
    @mbean_name = "oracle.as.soainfra.config:Location=ua_dv_soa_server1,name=bpel,type=BPELConfig,Application=soa-infra"
    display_mbean_attrs
  end
  
  def display_jta_attrs
    @mbean_name = "com.bea:Name=ua_dv_domain_1,Type=JTA"
    display_mbean_attrs
  end
  
  def get_mbean
	JMX::MBean.find_by_name @mbean_name
  end
  
  def get_object_name
	ObjectName.new @mbean_name
  end
  
  def get_mbean_attr_value(mbean_attr_name)
    @conn.get_attribute get_object_name, mbean_attr_name
  end
  
  def display_mbean_attrs
    get_mbean.attributes.each do |key, value|
      puts "Name: #{value}, Value: #{display_attribute_data(get_object_name, value)}\n"
    end
  end
  
  def to_s
    "JMXConnection [user=#{@user}, passwd=#{@passwd}, " +
	"url=#{@url}, " + "conn=#{@conn}]"
  end
  
  def display_array (value)
    data = ""
    value.each do |x|
      data += "\n\t" + x.to_s
    end
    return data
  end

  def display_attribute_data(object_name, attribute)   
    s = @conn.get_attribute object_name, attribute
    search_str = s.to_s
    
    if (/^\[Ljava.lang.String/.match(search_str)) or
      (/^\[I/.match(search_str)) or
      (/^\[Ljavax.management.ObjectName/.match(search_str))
      return display_array s
    end
    
    return s;
  end

  def test
    begin
      print "Run at #{Time.now} using JRuby #{RUBY_VERSION}\n"
      connect
      mbean = JMX::MBean.find_by_name @mbean_name
      puts "\n#{mbean.object_name}\n "
      mbean.attributes.each do |key, value|
	puts "Name: #{value}, Value: #{display_attribute_data(mbean.object_name, value)}\n"
      end
      
    rescue
      puts "\n** Error occured **\n"
      puts "Failed executing Oracle Weblogic JMX from JRuby ", $!, "\n"
    end
    
    print "\nEnded at #{Time.now}\n"
  end
end
  